package com.example.imtoken.modules.scanning

import android.content.Intent
import android.view.View
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.imtoken.R
import com.example.imtoken.core.OnMultifunctionalSelectorListener
import com.example.imtoken.core.base.BaseActivity
import com.example.imtoken.core.utils.Utils
import com.example.imtoken.databinding.ActivityScanningBinding
import com.example.imtoken.modules.main.my.address.create.CreateAddressActivity
import com.example.imtoken.modules.main.wallet.details.trade.transfer.TransferActivity
import com.example.imtoken.view.function.MultifunctionalSelectorDialogFragment
import com.example.imtoken.view.function.data.onFunction3
import com.mylhyl.zxing.scanner.ScannerOptions

/**
 * 扫描
 */
class ScanningActivity :
    BaseActivity<ScanningViewModel, ActivityScanningBinding>(ScanningViewModel::class.java) {

    private val operate by lazy {
        intent.getStringExtra("operate")
    }

    private val type by lazy {
        intent.getStringExtra("type")
    }

    override fun initLayoutId(): Int {
        return R.layout.activity_scanning
    }

    override fun init() {
        initBar(
            false
        )
        initTitle()
        initView()
        initClick()
        initListener()
    }

    private fun initTitle() {
        val layoutParams = dataBinding.view.layoutParams
        layoutParams.height = BarUtils.getStatusBarHeight()
        dataBinding.view.layoutParams = layoutParams
        dataBinding.include8.tvHeadTitles.text = getString(R.string.scanner)
        dataBinding.include8.clHeadHome.setBackgroundColor(ColorUtils.getColor(R.color.xui_transparent))
        dataBinding.include8.vLine.visibility = View.INVISIBLE
    }

    private fun initView() {
        //        dataBinding.svCode.toggleLight(true)
        val mScannerOptionsBuilder = ScannerOptions.Builder()
        mScannerOptionsBuilder.setTipText(getString(R.string.scannerTips))
        mScannerOptionsBuilder.setTipTextColor(ColorUtils.getColor(R.color.white))
        val scannerOptions = mScannerOptionsBuilder.build()
        dataBinding.svCode.setScannerOptions(scannerOptions)
    }

    private fun initListener() {
        dataBinding.svCode.setOnScannerCompletionListener { rawResult, _, _ ->
            if (rawResult.text.isNotEmpty()) {
                val content = rawResult.text
                try {
                    when (operate) {
                        "mnemonic" -> {
                            //导入助记词
                            val mnemonic = Utils.verifyMnemonic(content)
                            if (mnemonic != null) {
                                setResult(200, intent.putExtra("mnemonic", mnemonic))
                                this.finish()
                            } else {
                                ToastUtils.showShort(R.string.invalidMnemonicWords)
                                this.finish()
                            }
                        }
                        "private" -> {
                            //私钥导入
                            setResult(200, intent.putExtra("private", content))
                            this.finish()
                        }
                        "keyStore" -> {
                            //KeyStore导入
                            setResult(200, intent.putExtra("keyStore", content))
                            this.finish()
                        }
                        else -> {
                            val s1 = "ethereum:"
                            val s2 = "contractAddress="
                            val s3 = "decimal"
                            val s4 = "value"
                            val bal = content.startsWith(s1)
                            val address: String?
                            var contractAddress: String? = null
                            var decimal: String? = null
                            var value: String? = null
                            if (bal) {
                                address = content.substring(
                                    content.indexOf(s1) + s1.length,
                                    content.indexOf("?")
                                )
                                if (content.indexOf(s2) != -1) {
                                    contractAddress = content.substring(
                                        content.indexOf(s2) + s2.length,
                                        content.indexOf("&")
                                    )
                                }
                                val sb = content.substring(content.indexOf("?") + 1)
                                val sp = sb.split("&")
                                sp.forEach {
                                    val s = it.split("=")
                                    if (s.size == 2) {
                                        if (s[0] == s3) {
                                            decimal = s[1]
                                        } else if (s[0] == s4) {
                                            value = s[1]
                                        }
                                    }
                                }
                            } else {
                                address = content
                            }
                            when (type) {
                                "create_address" -> {
                                    setResult(100, intent.putExtra("address", address))
                                    finish()
                                }
                                "transfer_address" -> {
                                    if (bal) {
                                        intent.putExtra("address", address)
                                        intent.putExtra(
                                            "amount",
                                            Utils.initialAmountDivide(
                                                decimal?.toInt() ?: 0,
                                                value ?: "0"
                                            )
                                        )
                                        setResult(100, intent)
                                        finish()
                                    } else {
                                        setResult(100, intent.putExtra("address", address))
                                        finish()
                                    }
                                }
                                else -> {
                                    if (bal) {
                                        if (contractAddress == null) {
                                            val intent = Intent(
                                                this@ScanningActivity,
                                                TransferActivity::class.java
                                            )
                                            intent.putExtra("title", "ETH")
                                            intent.putExtra("coin", "eth")
                                            intent.putExtra("address", address)
                                            intent.putExtra(
                                                "amount",
                                                Utils.initialAmountDivide(
                                                    decimal?.toInt() ?: 0,
                                                    value ?: "0"
                                                )
                                            )
                                            ActivityUtils.startActivity(intent)
                                            finish()
                                        } else {
                                            val intent = Intent(
                                                this@ScanningActivity,
                                                TransferActivity::class.java
                                            )
                                            intent.putExtra("title", "USDT")
                                            intent.putExtra("coin", "usdt")
                                            intent.putExtra("contractAddress", contractAddress)
                                            intent.putExtra("address", address)
                                            intent.putExtra(
                                                "amount",
                                                Utils.initialAmountDivide(
                                                    decimal?.toInt() ?: 0,
                                                    value ?: "0"
                                                )
                                            )
                                            ActivityUtils.startActivity(intent)
                                            finish()
                                        }
                                    } else {
                                        val dialog = MultifunctionalSelectorDialogFragment()
                                        dialog.setData(onFunction3(), object :
                                            OnMultifunctionalSelectorListener {
                                            override fun selectPosition(position: Int) {
                                                when (position) {
                                                    0 -> {
                                                        //转账
                                                        val intent = Intent(
                                                            this@ScanningActivity,
                                                            TransferActivity::class.java
                                                        )
                                                        intent.putExtra("title", "ETH")
                                                        intent.putExtra("coin", "eth")
                                                        intent.putExtra("address", address)
                                                        ActivityUtils.startActivity(intent)
                                                    }
                                                    1 -> {
                                                        //新建地址
                                                        val intent = Intent(
                                                            this@ScanningActivity,
                                                            CreateAddressActivity::class.java
                                                        )
                                                        intent.putExtra("coin", "eth")
                                                        intent.putExtra("address", address)
                                                        ActivityUtils.startActivity(intent)
                                                    }
                                                }
                                                finish()
                                            }

                                        })
                                        dialog.show(supportFragmentManager, "dialog")
                                    }
                                }
                            }
                        }
                    }
                } catch (e: Exception) {
                    ToastUtils.showShort(getString(R.string.scanningTips1))
                }
            } else {
                ToastUtils.showShort(getString(R.string.scanningTips))
            }
        }
    }

    private fun initClick() {
        dataBinding.include8.ivHeadBack.setOnClickListener { this.finish() }
    }

    override fun onResume() {
        dataBinding.svCode.onResume()
        super.onResume()
    }

    override fun onPause() {
        dataBinding.svCode.onPause()
        super.onPause()
    }

}